<template>
  <a-modal
    title="申请专属任务"
    :width="700"
    :visible="visible"
    @ok="handleModalConfirm"
    @cancel="handleModalCancel"
    :confirm-loading="modalLoading"
    @after-open="saveFocusedElement"
    @after-close="restoreFocusedElement"
  >
    <a-form-model
      ref="form"
      :model="form"
      :rules="formRules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <a-form-model-item label="目标销售额" prop="sale_money">
        <a-input
          v-model="form.sale_money"
          placeholder="请输入"
          allowClear
          suffix="万"
          type="number"
          @change="handleChangeSale_money"
        />
      </a-form-model-item>

      <a-form-model-item label="任务补贴比例" prop="promotion_money_rate">
        <a-input
          v-model="form.promotion_money_rate"
          placeholder="请输入"
          allowClear
          suffix="%"
          type="number"
          @change="handleChangePromotion_money_rate"
        />
      </a-form-model-item>

      <a-form-model-item label="*预计补贴" v-if="money_toflex">
        <div class="title" style="color: #E33B35;">¥{{ money_toflex }}</div>
      </a-form-model-item>
      
      <a-form-model-item label="选择达人" prop="ks_user_id_json_box">
        <a-select
          v-model="form.ks_user_id_json_box"
          :get-popup-container="getPopupContainer"
           mode="multiple"
          @popupScroll="handlePopupScroll"
          placeholder="请选择达人"
          @change="handleSelectChange"
          v-if="customersListOptions.length > 0"
        >
          <a-select-option
            v-for="user in customersListOptions"
            :key="user.ks_user_id"
            :value="user.ks_user_id"
            :disabled="user.is_join === 1"
          >
            <div style="display: flex; align-items: center">
              <img
                :src="
                  user.portrait
                    ? processImage(user.portrait)
                    : processImage(
                        '/storage/app_icon/20241115/8db41e60976fb7f1210af4e19c2122cb.png'
                      )
                "
                alt="avatar"
                style="
                  width: 30px;
                  height: 30px;
                  margin-right: 8px;
                  border-radius: 50%;
                "
              />
              <span class="nickname">{{ user.nickname }}</span> (ID:
              {{ user.ks_user_id }})
              <span class="delivery_rate"
                >申样交付率: {{ user.delivery_rate }}%</span
              >
            </div>
          </a-select-option>
        </a-select>
      </a-form-model-item>
     
      
      <a-form-model-item label="预计直播时间" prop="live_time">
        <a-range-picker @change="onChange" v-model="form.live_time" />
      </a-form-model-item>
    
      
     
      
     
    </a-form-model>
   
  </a-modal>
</template>

<script>
import * as Ajax from "@/api/channel";
import areaSelect from "./areaselect";
import areaData from "./areaData";
import { mapState, mapGetters } from "vuex";
export default {
  props: {
    task_uuid: {
      type: String,
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    detailsInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    areaSelect,
  },
  data() {
    return {
      modalLoading: false,
      form: {
        ks_user_id_json_box: [],
        sale_money: "",
        promotion_money_rate: "",
        task_uuid: "",
        start_time:"",
        end_time:"",
        ks_user_id_json:[],
      },
      formRules: {
        
        promotion_money_rate: {
          required: true,
          message: "请输入任务补贴比例",
          trigger: ["blur", "change"],
        },
        address_id: {
          required: true,
          message: "请选择地址",
          trigger: ["blur", "change"],
        },
        ks_user_id_json_box: {
          required: true,
          message: "请选择达人",
          trigger: ["blur", "change"],
        },
        normal_special: [
          { required: true, message: "请选择是否发货", trigger: "change" },
        ],
        link_property: [
          { required: true, message: "请选择属性链接", trigger: "change" },
        ],
        sale_money: {
          required: true,
          message: "请输入目标销售额",
          trigger: ["blur", "change"],
        },
        live_time: [
          { required: true, message: "请选择预计直播时间", trigger: "change" },
          {
            validator: this.validateTimeRange,
            trigger: "change",
          },
        ],
      },
      form2: {
        consignee: "",
        mobile: "",
        province_name: "",
        city_name: "",
        district_name: "",
        address: "",
        defaultArea: [],
        is_default: false,
        promotionId: null,
        institution_uuid: null,
      },
      formRules2: {
      // 其他规则
      consignee: [
        { required: true, message: '请输入收货人', trigger: 'blur' },
      ],
      mobile: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' },
      ],
      province_name: [
        { required: true, message: '请选择所在地区', trigger: 'change' },
      ],
      address: [
        { required: true, message: '请输入详细地址', trigger: 'blur' },
      ],
    },
      
      addressOptions: [],
      focusedElement: null,
      testInfo: {
        order_count: "",
        commission: "",
        commission2: "",
      },
      tipShow: false,
      page: 1,
      customersListOptions: [],
      noMoreData: false,
      loadStatus: "加载更多",
      promotionId: null,
      institution_uuid: null,
      plainOptions: [
        {
          productId: 1,
          productName: "是",
        },
        {
          productId: 2,
          productName: "否",
        },
      ],
      statsLink: [
        {
          linkStats: 1,
          linkName: "公开",
        },
        {
          linkStats: 2,
          linkName: "专属",
        },
      ],
      product_info: {},
      visibleAddress: false,
      defaultArea: [],
      areaData,
      money_toflex: 0,
    };
  },
  computed: {
    ...mapGetters("user", ["getCdnUrl", "getUserInfo"]),
  },
  methods: {
    processImage(imageUrl) {
      if (imageUrl === undefined || imageUrl === null) {
        return ""; // 或者返回一个默认的 URL
      }

      if (!imageUrl.startsWith("http")) {
        return this.getCdnUrl + imageUrl;
      }
      return imageUrl;
    },
    handleModalConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.task_uuid = this.task_uuid;
          this.form.ks_user_id_json = JSON.stringify(this.form.ks_user_id_json_box)
          
          this.taskApply();
        } else {
          console.log("表单验证失败");
        }
      });
    },
    validateTimeRange(rule, value, callback) {
      if (!value || value.length !== 2) {
        callback(new Error("请选择完整的开始和结束时间"));
      } else {
        const [startTime, endTime] = value;
        if (startTime.isAfter(endTime)) {
          callback(new Error("开始时间不能晚于结束时间"));
        } else {
          callback();
        }
      }
    },
    get_receiveEstimate() {
      Ajax.receiveEstimate({
        sale_money: this.form.channelName,
        task_uuid: this.task_uuid,
      }).then((res) => {
        console.log("res.error", res.error);

        if (res.error === 0) {
          this.testInfo.commission = res.data.commission;
          this.testInfo.commission2 =
            (res.data.commission - 0) /
            (this.level_task_commission_rate - 0 * 0.01);
          this.testInfo.order_count = res.data.order_count;
          this.tipShow = true;
        }
      });
    },
    handleModalCancel() {
      this.form = this.$options.data().form;
      this.$refs.form.resetFields();
      this.$emit("close");
      this.money_toflex = 0;
    },
    saveFocusedElement() {
      this.focusedElement = document.activeElement;
    },
    restoreFocusedElement() {
      if (this.focusedElement) {
        this.focusedElement.focus();
      }
    },
    handleChange() {
      this.get_receiveEstimate();
    },
    handleChangeSale_money() {
      if (this.form.sale_money< 1) {
        this.form.sale_money = 1;
        this.$message.error("销售金额不能小于1万元");
      }
      this.money_toflex = ( this.form.sale_money*10000) * (this.form.promotion_money_rate/100);
    },
    handleChangePromotion_money_rate() {
      
      this.money_toflex = (this.form.sale_money*10000) * (this.form.promotion_money_rate/100);
    },
    onChange(date, dateString) {
      console.log(date, dateString);
      this.form.start_time = dateString[0] + " 00:00:00";
      this.form.end_time = dateString[1] + " 23:59:59";
    },
    handleChange2(value) {
      console.log(`selected ${value}`);
    },
    get_customersList() {
      Ajax.customersList({
        page: this.page,
        list_rows: 10,
      }).then((res) => {
        console.log("res.error", res.error);
        if (res.error === 0) {
          this.customersListOptions = [
            ...this.customersListOptions,
            ...res.data.data,
          ];
          if (res.data.current_page < res.data.last_page) {
            this.loadStatus = "加载更多";
            this.noMoreData = false;
            this.page += 1;
          } else {
            this.loadStatus = "没有更多了";
            this.noMoreData = true;
          }
        }
      });
    },
    get_address() {
      Ajax.address({
        promotionId: this.promotionId,
        institution_uuid: this.institution_uuid,
      }).then((res) => {
        if (res.error === 0) {
          this.addressOptions = res.data;
          // 确保 addressOptions 有数据后再设置默认值
          if (this.addressOptions.length > 0) {
            this.form.address_id = this.addressOptions[0].id;
          }
        } else {
          console.error("获取地址失败", res);
        }
      }).catch((error) => {
        console.error("获取地址时发生错误", error);
      });
    },
    getPopupContainer(triggerNode) {
      return triggerNode.parentNode;
    },
    handlePopupScroll(value) {
      const { scrollHeight, scrollTop, clientHeight } = value.target;
      if (scrollHeight - scrollTop === clientHeight && !this.noMoreData) {
        this.get_customersList(this.page);
      }
    },
    async handleSelectChange(value) {
      // 找到所选的达人信息
      console.log("value", value);
     
    },
    addressChange(value) {
      console.log("addressChange", this.form.address_id);
      // this.form.address_id = value;
    },
   
    taskApply() {
      Ajax.taskApply(this.form).then((res) => {
        console.log("res.error", res.error);
        if (res.error === 0) {
          this.$message.success(res.msg);
          this.handleModalCancel();
        }
      });
    },
 
    
   
    
   
  },
  mounted() {
    this.get_customersList();
  },
 
};
</script>

<style lang="scss" scoped>
.table-wrap {
  margin-top: 20px;
  padding-top: 16px;
}

.btn-gruop {
  display: flex;
  justify-content: flex-end;
}

::v-deep .ant-form-item {
  &:last-child {
    margin-bottom: 0;
  }
}
::v-deep .ant-input-number-input {
  text-align: center !important;
}
::v-deep .address_box .ant-select-selection--single {
  position: relative;
  height: 64px;
  cursor: pointer;
}

::v-deep  .ant-select-selection--multiple .ant-select-selection__rendered > ul > li {
    height: 30px;
    margin-top: 3px;
    line-height: 22px;
}

.tips_box {
  padding: 4px;
}
.text {
  // font-size: 16px;
  color: #999999;
  margin: 10px 0;
  // text-align: center;
  span {
    color: #e33b35;
  }
}
.sale {
  display: flex;
  align-items: center;
  margin-left: 4px;
  margin-bottom: 10px;
  div {
    font-size: 14px;
    span {
      color: #e33b35;
    }
  }
}
.product_information {
  display: flex;
  img {
    width: 110px;
    height: 110px;
    border-radius: 8px;
    margin-right: 10px;
  }
  .product_info {
    .product_name {
      font-weight: 400;
      font-size: 15px;
      color: #666666;
      display: -webkit-box;
      line-height: 21px;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .product_price {
      P {
        font-weight: 600;
        font-size: 12px;
        color: #e33b35;
        margin-bottom: 8px;
        span:nth-child(2) {
          font-size: 18px;
        }
      }
      p:nth-child(2) {
        font-weight: 400;
        font-size: 15px;
        color: #666666;
        line-height: 21px;
      }
    }
  }
}
.input_box {
  display: flex;
  align-items: center;
  .minus_btn {
    width: 30px;
    height: 32px;
    border-radius: 6px 0px 0px 6px;
    border-top: 1px solid #cbcbcb;
    border-left: 1px solid #cbcbcb;
    border-bottom: 1px solid #cbcbcb;
    text-align: center;
    line-height: 30px;
    cursor: pointer;
  }
  .add_btn {
    width: 30px;
    height: 32px;
    border-radius: 0px 6px 6px 0px;
    border-top: 1px solid #cbcbcb;
    border-right: 1px solid #cbcbcb;
    border-bottom: 1px solid #cbcbcb;
    text-align: center;
    line-height: 30px;
    cursor: pointer;
  }
}
.nickname {
  display: inline-block;
  max-width: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 10px;
}
.delivery_rate {
  margin-left: 10px;
  display: inline-block;
  color: #e33b35;
  border-radius: 4px;
  font-size: 12px;
}
.address_btn {
  width: 96px;
  height: 32px;
  background: #f1f8ff;
  border-radius: 4px;
  text-align: center;
  font-weight: 400;
  font-size: 15px;
  color: #1890ff;
  line-height: 32px;
  cursor: pointer;
  margin-left: 14px;
}
.link_box {
  .link_item {
    display: flex;
    align-items: center;
    margin-right: 10px;
  }
  img {
    width: 16px;
    height: 16px;
    cursor: pointer;
  }
  .link_desc {
    font-size: 12px;
    color: #666666;
    margin-top: 4px;
  }
}
.tips_content {
  margin-left: 102px;
  font-weight: 400;
  font-size: 13px;
  color: #e33b35;
}
</style>